<?php
/*
 * @Description:
 * @Autor: wangjt
 * @Date: 2020-04-06 17:12:12
 * @LastEditors: wangjt
 * @LastEditTime: 2020-04-21 14:17:40
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;
// use \Auth;
use Illuminate\Support\Facades\Auth;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', [
            'except' => ['index', 'show', 'create', 'store']
        ]);

        $this->middleware('guest', [
            'only' => ['create']
        ]);
    }

    public function index()
    {
        $users = User::paginate(10);
        return view('user.index', compact('users'));
    }

    public function show(User $user)
    {
        return view('user.show', compact('user'));
    }

    public function create() {
        return view('user.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' =>'required|unique:users|max:50',
            'email' => 'required|email|unique:users|max:255',
            'password' => 'required|confirmed|min:6'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
        Auth::login($user);
        session()->flash('success', '欢迎， 您将在这里开启一段新的旅程');
        return redirect()->route('users.show', [$user]);
    }

    public function edit(User $user)
    {
        $this->authorize('update', $user);
        return view('user.edit', compact('user'));
    }

    public function update(User $user, Request $request)
    {
        $this->authorize('update', $user);
        $this->validate($request, [
            'name'=>'required|max:50',
            'password'=> 'nullable|confirmed|min:6'
        ]);

        $user->update([
            'name'=>$request->name,
            'password'=>bcrypt($request->password)
        ]);

        session()->flash('success', '个人资料更新成功！');

        return redirect()->route('users.show', $user->id);
    }

    // 删除
    public function destroy(User $user)
    {
        $user->delete();
        session()->flash('success', '成功删除用户');
        return back();
    }
}
